PAT--甲 1063 Set Similarity

甲 1063 Set Similarity (题解)

Given two sets of integers, the similarity of the sets is defined to be Nc/Nt×100%, where ​c is the number of distinct common numbers shared by the two sets, and Nt is the total number of distinct numbers in the two sets. Your job is to calculate the similarity of any given pair of sets.

输入格式:

Each input file contains one test case. Each case first gives a positive integer N (≤50) which is the total number of sets. Then N lines follow, each gives a set with a positive M (≤10​4 ) and followed by M integers in the range [0,10 9]. After the input of sets, a positive integer K (≤2000) is given, followed by K lines of queries. Each query gives a pair of set numbers (the sets are numbered from 1 to N). All the numbers in a line are separated by a space.

输出格式:

For each query, print in one line the similarity of the sets, in the percentage form accurate up to 1 decimal place.

1
2
3
4
5
6
7
3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3
复制

输出样例:

1
2
50.0%
33.3%
复制

思路:

用set解题 求两个集合的交集和并集

我的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<bits/stdc++.h>
using namespace std;
const int N=55;
set<int>s[N];
void compare(int a,int b)
{
int tn=s[a].size(),sn=0;//分别记录并集和交集元素的个数
for(set<int>::iterator it=s[b].begin();it!=s[b].end();it++)
{
if(s[a].find(*it)!=s[a].end())
sn++;
else
tn++;
}
printf("%.1f%%",sn*100.0/tn);//%%输出 %号
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
int m,x;
scanf("%d",&m);
for(int j=0;j<m;j++)
{
scanf("%d",&x);
s[i].insert(x);
}
}
int k,x,y;
scanf("%d",&k);
for(int i=0;i<k;i++)
{
scanf("%d%d",&x,&y);
compare(x,y);
if(i!=k-1)
printf("\n");
}
return 0;
}
复制
小礼物走一个哟

Related Issues not found

Please contact @Daybreak-Zheng to initialize the comment

0%